import { VMCustomEntity } from "./VMCustomEntity";
import { VM } from "../VMMgr";
import * as cc from "cc";
import { VMEventAttr } from "../VMEntity";

declare const CC_EDITOR;
declare const CC_DEV;

export class VMEventEntity extends VMCustomEntity{
    // @ts-ignore
    observerAttr: VMEventAttr;
    onBind() {
        if(CC_EDITOR){ return; }
     
    }
    onUnBind() {
        if(CC_EDITOR){ return; }
     
    }
    
    onValueInit() {
        if(CC_EDITOR){ return; }
        let _watchPath = this.observerAttr.watchPath;
        if(Array.isArray(_watchPath)){
            let max = _watchPath.length;
            for (let i = 0; i < max; i++) {
                let val = VM.getValue(_watchPath[i],null);
                this.templateValuesCache[i] = val;
            }
            this._updateValue(this.templateValuesCache,null,_watchPath);
        }else{
            let val = VM.getValue(_watchPath as string);
            this._updateValue(val,null,_watchPath);
        }
    }
    onStart() {
        if(CC_EDITOR){ return; }
        
    }
    
    protected onValueChanged(newValue: any, oldValue: any, pathArr: readonly string[]) {
        if(CC_EDITOR){ return; }
        let path = pathArr.join('.');
        let _watchPath = this.observerAttr.watchPath;
        if(Array.isArray(_watchPath)){
            let _oldValue = [...this.templateValuesCache];
            //寻找缓存位置
            let index = _watchPath.findIndex(v => v === path);
            if (index >= 0) {
                //如果是所属的路径，就可以替换文本了
                this.templateValuesCache[index] = newValue; //缓存值
            }
            this._updateValue(this.templateValuesCache,_oldValue,_watchPath); // 重新解析
        }else{
            this._updateValue(newValue,oldValue,path);
        }
    }
    _updateValue(newValue,oldValue,watchPath){
        let _onChangeEvent = this.observerAttr.onChangeEvent || this.observerAttr.formator;
        if(!_onChangeEvent){
            console.warn(`VMFactory->VMEventEntity [${this.node.name}] have not onChangeEvent, emit event fail !`);            
            return;
        }
        _onChangeEvent.call(this.controllerUserComponent,{
            entity: this,
            newValue,
            oldValue,
            node: this.node,
            nodeIdx :0,
            watchPath,
        });
    }
    onCheckProperty(): boolean {
        return true;
    }

}
